/**
 * Created with JetBrains PhpStorm.
 * User: MeRo
 * Date: 14.09.13
 * Time: 18:30
 * To change this template use File | Settings | File Templates.
 */

function addToUrl(url, paramKey, paramValue) {
    var separator = '';
    if (url.indexOf('?') >= 0) {
        separator = '&';
        if (url.substring(url.length - 1, url.length) == '&') {
            separator = '';
        }

        url = url + separator + encodeURI(paramKey) + '=' + encodeURI(paramValue);
    } else {
        separator = '?';
        if (url.substring(url.length - 1, url.length) == '?') {
            separator = '';
        }

        url = url + separator + encodeURI(paramKey) + '=' + encodeURI(paramValue);
    }

    return url;
}

function validateInput(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode(key);
    var regex = /[0-9]|\./;
    if (!regex.test(key)) {
        theEvent.returnValue = false;
        if (theEvent.preventDefault) {
            theEvent.preventDefault();
        }
    }
}

$(document).ready(function() {
    $('#start .gridly').gridly({
        base: 150, // px
        gutter: 5, // px
        columns: 7
    });

    var loadSurfaceGrids = $('#load_surface .gridly>div').length;
    var width = loadSurfaceGrids * 150 + (loadSurfaceGrids - 1) * 5;
    if (width > 1080) {
        width = 1080;
    }

    $('.crazyMove').on('mouseover', function() {
        var direction = Math.floor((Math.random()*4)+1);
        var val = 155;

        switch(direction) {
            case 1:
                $(this).css('margin-top', val);
                break;
            case 2:
                $(this).css('margin-bottom', val);
                break;
            case 3:
                $(this).css('margin-left', val);
                break;
            case 4:
                $(this).css('margin-right', val);
                break;
        }
    });

    $('textarea').autogrow;

    var startLinkIsClicked = false;
    $('#start .gridly .brick a').on('click', function(e) {
        if (startLinkIsClicked === false) {
            startLinkIsClicked = true;
            $(this).parent().addClass('white');
            $(this).parent().find('.loadContainer').addClass('loading');
            $(this).remove();
            setTimeout(function() {
                $('.gridly .loading').fadeIn( "slow", function() {
                });
            }, 100);
        } else {
            e.preventDefault();
        }
    });

    $('#newSurfaceForm').find('input[type="number"]').on('input', function() {
        this.value=this.value.replace(/[^\d]/,'');
    });

    var newSurfaceIsLocked = false
    $('#new_surface').find('input[type="submit"]').on('click', function(e) {
        e.preventDefault();
        if (newSurfaceIsLocked == false) {
            $(this).css('background-image', 'url("files/train/img/icon/load.gif")');
            newSurfaceIsLocked = true;

            var url = 'de/ajax/articles/new_surface_validation';

            $('#newSurfaceForm').find('input, textarea').each(function(key, val) {
                if ($(val).attr('type') == 'text' || $(val).attr('type') == 'number' || $(val).attr('rows')) {
                    url = addToUrl(url, val.name, val.value);
                } else if ($(val).attr('type') == 'checkbox') {
                    if ($(val).is(':checked')) {
                        url = addToUrl(url, val.name, 1);
                    } else {
                        url = addToUrl(url, val.name, 0);
                    }
                }
            });

            $.getJSON(url, function(data) {
                $('#new_surface')
                    .find('input[type="submit"]')
                    .css('background-image', 'url("files/train/img/icon/add.png")')
                ;

                $('#errorlog ul').html('');
                $('#newSurfaceForm').find('input, textarea').removeClass('mandatory');
                if (typeof data['errors'] != 'undefined') {
                    $.each(data['errors'], function(key, val) {
                        $('#errorlog ul').append('<li>' + val + '</li>');
                    })

                    $.each(data['fields'], function(key, val) {
                        $('#newSurfaceForm')
                            .find('input[name=' + key + '], textarea[name=' + key + ']')
                            .addClass('mandatory')
                        ;
                    })
                } else if (data['id'] != 'undefined') {
                    $('#new_surface').html('');
                    generateSurface(data);
                } else {
                    $('#new_surface>div').html('<h1>ERROR: main.js:105</h1>');
                }

                newSurfaceIsLocked = false;
            });
        }
    });

    $('.autoscroll').on('mousemove', function(e) {
        var height      = $(this).height() + 13;
        var offset      = $(this).offset();
        var position    = (e.pageY-offset.top)/height;

        if (position < 0.33) {
            $(this).stop().animate({ scrollTop: 0 }, 500);
        } else if (position > 0.66) {
            $(this).stop().animate({ scrollTop: height }, 500);
        }
    });

    $('#load_surface .gridly .brick').on('click', function() {
        generateSurface(jQuery.parseJSON($(this).find('.data').html()));
        $('#load_surface').html('');
    });
});
